import React, { useState, useEffect, useMemo } from 'react'
import { useQuery } from 'remax'
import { Image, Text, View } from 'remax/one'
import { usePageEvent } from 'remax/macro'
import {
  cloud,
  MovableArea,
  MovableView,
  navigateToMiniProgram,
  setClipboardData,
  showToast,
} from 'remax/wechat'
import { Button, Space, Tag } from 'annar'
import getDistance from '@turf/distance'
import useCloud, { requestCloud } from '@/hooks/use-cloud'
import useLocation from '@/hooks/use-location'
import Login from '@/components/login'
import styles from './index.css'

const db = cloud.database()
const result: object[] = []

export default () => {
  const { _id } = useQuery()
  const [config, setConfig] = useState({
    eventName: '',
    cipher: '',
    distance: 10,
    location: [],
    wechat: '',
    guideImgUrl: '',
    shareImgUrl: '',
    miniProgram: { appId: '', path: '' },
  })
  useEffect(() => {
    ;(async () => {
      const { data: cData } = await db.collection('vote-config').get()
      if (cData && cData[0]) {
        setConfig(cData[0])
      }
      if (_id) {
        const {
          data: [starter],
        } = await db.collection('vote-starter').where({ _id }).get()
        const { data: iData } = await db.collection('vote-invite').get()
        if (!iData.length) {
          await db.collection('vote-invite').add({
            data: {
              starter,
              createAt: db.serverDate(),
              success: true,
            },
          })
        }
      } else {
        await db
          .collection('vote-invite')
          .where({ _openid: db.command.neq('') })
          .update({
            data: { success: true },
          })
      }
    })()
  }, [])

  const { location } = useLocation()
  const distance = useMemo(() => {
    if (!location || !config.location.length) {
      return null
    } else {
      const from = [location.longitude, location.latitude]
      const to = config.location
      return getDistance(from, to)
    }
  }, [location, config])

  const { data: rawData } = useCloud(location ? 'list-promotion' : null, {
    audit: 1,
    koi: true,
  })
  const [point, setPoint] = useState([0, 0])
  const [curX, setCurX] = useState(0)
  const [curIndex, setCurIndex] = useState(0)
  const [success, setSuccess] = useState<Boolean>()

  usePageEvent('onShareAppMessage', async () => {
    return {
      title: config.eventName,
      path: '/pages/vote-event/index' + (_id ? `?_id=${_id}` : ''),
      imageUrl: config.shareImgUrl,
    }
  })

  if (curIndex === 0) {
    result.length = 0
  }
  if (!distance || !rawData || !rawData[0]) {
    return null
  }

  const data =
    rawData &&
    rawData.map((v: any) => ({
      _id: v._id,
      name: v.name,
      price: v.price,
      originalPrice: v.originalPrice,
      imgUrl: v.imgUrls[0],
    }))

  const onTouchEnd = () => {
    if (Math.abs(curX) > 40) {
      result.push({ ...data[curIndex], like: curX > 0 })
      if (!data[curIndex + 1]) {
        vote()
      }
      setCurIndex(curIndex + 1)
    }
    setPoint([point[0] ? 0 : 0.01, 0])
  }

  const vote = async () => {
    try {
      await requestCloud('add-vote-result', { result })
      setSuccess(true)
    } catch ({ errMsg }) {
      if (/vote only once/.test(errMsg)) {
        setSuccess(true)
      } else {
        showToast({ title: '网络错误', icon: 'none' })
        setSuccess(false)
      }
    }
  }

  return (
    <Login>
      <View className={styles.mainArea}>
        {distance && distance > config.distance ? (
          <>
            <View className={styles.desc}>
              您离学校超过 {config.distance} 公里，无法参与投票
            </View>
          </>
        ) : success === true ? (
          <>
            <Space size={12}>
              <Text>请您添加客服微信：{config.wechat}</Text>
              <Button
                look="secure"
                size="small"
                onTap={() => {
                  setClipboardData({ data: config.wechat })
                }}
              >
                复制
              </Button>
            </Space>
            <View>
              注意：开奖前未添加客服微信
              <Text className="alarm-text">无法领奖</Text>！
            </View>
            <Image
              className={styles.guideImg}
              src={config.guideImgUrl}
              mode="widthFix"
            />
            <View>您已完成投票，获得抽奖口令</View>
            <View className={`${styles.desc} large-text alarm-text`}>
              <Text selectable>{config.cipher}</Text>
            </View>
            <Text className={`${styles.desc} large-text`}>最后一步！</Text>
            <Button
              look="secure"
              size="large"
              onTap={() => {
                navigateToMiniProgram(config.miniProgram)
              }}
            >
              输入抽奖码
            </Button>
          </>
        ) : success === false ? (
          <>
            <View className={styles.desc}>投票结果发送失败</View>
            <Button
              look="secure"
              size="large"
              onTap={() => {
                vote()
              }}
            >
              重新发送投票结果
            </Button>
          </>
        ) : (
          data[curIndex] && (
            <>
              <View>
                <Text
                  className={
                    curX < -5 ? 'xlarge-text alarm-text' : 'large-text'
                  }
                >
                  左划无感
                </Text>
                <Text
                  className={curX > 5 ? 'xlarge-text safe-text' : 'large-text'}
                  style={{ marginLeft: 50 }}
                >
                  右划喜欢
                </Text>
              </View>
              <MovableArea className={styles.movableArea}>
                <MovableView
                  className={styles.movableView}
                  style={{ zIndex: 0 }}
                  direction="all"
                  animation={false}
                  x={point[0]}
                  y={point[1]}
                  onChange={e => {
                    setCurX(e.detail.x)
                  }}
                >
                  <Image
                    className={styles.img}
                    src={data[curIndex].imgUrl}
                    mode="widthFix"
                    onTouchEnd={onTouchEnd}
                    onTouchCancel={onTouchEnd}
                  />
                  <View
                    className={styles.desc}
                    onTouchEnd={onTouchEnd}
                    onTouchCancel={onTouchEnd}
                  >
                    <View className="xlarge-text ellipsis">
                      {data[curIndex].name}
                    </View>
                    <Space align="center" size={12}>
                      <Text className="large-text alarm-text">
                        {data[curIndex].price}
                      </Text>
                      <Text className="deleted-text">
                        {data[curIndex].originalPrice}
                      </Text>
                      <Tag className="no-border" color="red">
                        {Math.round(
                          (data[curIndex].price /
                            data[curIndex].originalPrice) *
                            100
                        ) / 10}{' '}
                        折
                      </Tag>
                    </Space>
                  </View>
                </MovableView>
                )
                {data[curIndex + 1] && (
                  <View className={styles.movableView} style={{ zIndex: -1 }}>
                    <Image
                      className={styles.img}
                      src={data[curIndex + 1].imgUrl}
                      mode="widthFix"
                    />
                    <View className={styles.desc}>
                      <View className="xlarge-text ellipsis">
                        {data[curIndex + 1].name}
                      </View>
                      <Space align="center" size={12}>
                        <Text className="large-text alarm-text">
                          {data[curIndex + 1].price}
                        </Text>
                        <Text className="deleted-text">
                          {data[curIndex + 1].originalPrice}
                        </Text>
                        <Tag className="no-border" color="red">
                          {Math.round(
                            (data[curIndex + 1].price /
                              data[curIndex + 1].originalPrice) *
                              100
                          ) / 10}{' '}
                          折
                        </Tag>
                      </Space>
                    </View>
                  </View>
                )}
              </MovableArea>
              <View>
                {curIndex + 1} / {data.length}
              </View>
            </>
          )
        )}
      </View>
    </Login>
  )
}
